#!/bin/bash
#pMusic - play engine
#GPL - Copyright Sigmund Berglund

export TEXTDOMAIN=pmusic
export OUTPUT_CHARSET=UTF-8
alias wget='wget -U "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15" -t 1 --connect-timeout=1'

case "$1" in
-jamendo_top100)
	[ "$2" ] && GENRE="&tag_idstr=$2"
	#check internet connection
	LANG=C wget --spider --tries 1 -T 3  -F --max-redirect 0 "http://www.jamendo.com" 2> $WORKDIR/tmpinfo
	if [[ "$(<$WORKDIR/tmpinfo)" != *connected* ]]; then
		echo "|$(gettext 'No connection to jamendo.com')" > $WORKDIR/tmp_sourcelist
	else
		wget --tries 1 -O - "http://api.jamendo.com/get2/id+artist_name+name+album_name+numalbum+dates+genre+duration/track/plain/track_album+album_artist/?n=100&order=ratingweek_desc${GENRE}" | tr '\t' '|' | sed -e 's/Array//g' -e 's/^/http:\/\/api.jamendo.com\/get2\/stream\/track\/redirect\/?streamencoding=mp31\&id=/g' -e 's/$/|||||||gtk-audio/g' > $WORKDIR/tmp_sourcelist
	fi
	$APPDIR/func -add_to_history "pMusic: Jamendo.com $2" & #update history
	mv -f $WORKDIR/tmp_sourcelist $WORKDIR/sourcelist
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;
-build_jamendo_index)
	LC_ALL=C wget --tries=1 -O $WORKDIR/tmp_jamendo_dump.gz http://imgjam.com/data/dbdump_artistalbumtrack.xml.gz
	gunzip $WORKDIR/tmp_jamendo_dump.gz
	COUNT=0
	TOTAL=`grep -c "^" $WORKDIR/tmp_jamendo_dump`
	echo "preparing input data..."
	echo -n > "$STORAGE_DIR"/index_jamendo
	while read I; do #read index file line by line (artist by artist)
		#split all xml tags into newlines
		echo "$I" | tr '>' '\n' | grep -E "<album|</album|</id|</name|</releasedate|</id3genre|</numalbum|</track|</duration" > $WORKDIR/tmp_jamendo
		#find artist
		IFS='<' read ARTIST TMP <<< "`grep -Fm1 '</name' $WORKDIR/tmp_jamendo`"
		#give some progress output
		PERCENT=$(($COUNT*100/$TOTAL))
		echo "$COUNT(${PERCENT}%) `grep -c "^" "$STORAGE_DIR/index_jamendo"` $ARTIST"
		COUNT=$(($COUNT+1))
		#find albums
		grep -FA3 '<album' $WORKDIR/tmp_jamendo | grep -F '</name' | cut -d'<' -f1 > $WORKDIR/tmp_jamendo_albums
		while read ALBUM; do
			grep -A100 -Fm1 "$ALBUM" $WORKDIR/tmp_jamendo | tac | head -n -1 | tac > $WORKDIR/tmp_jamendo2
			while read J; do
				case "$J" in
					*"</album")	#we have reach next album
						break
						;;
					*"</id")
						ID=${J%%<*}
						;;
					*"</name")
						TITLE=${J%%<*}
						;;
					*"</releasedate")
						YEAR=${J%%<*}; YEAR=${YEAR%%-*}
						;;
					*"</numalbum")
						TRACK=${J%%<*}
						;;
					*"</duration")
						TMP=${J%%<*}; TMP=${TMP%%.*}
						MIN=$(($TMP/60))
						SEC=$(($TMP-($MIN*60)))
						LENGTH=$(printf "%02d" $MIN):$(printf "%02d" $SEC)
						;;
					*"</id3genre")
						TMP=${J%%<*}
						if [ "$TMP" ] && [ "$TMP" != "0" ]; then #if album_id3 is set, track_id3 could be set to 0
							GENRE="`grep "^${TMP}|" $APPDIR/txt_id3genre | cut -d'|' -f2`"
						fi
						;;
					*"</track")
						 #add item to index
						 echo "+${ID}|$ARTIST|$TITLE|$ALBUM|$TRACK|$YEAR|$GENRE||||96|$LENGTH" >> "$STORAGE_DIR/index_jamendo"
						;;
				esac
			done < $WORKDIR/tmp_jamendo2
			GENRE='' #not all items/albums has genre defined, so we clear it to avoid duplication in next album
		done < $WORKDIR/tmp_jamendo_albums
	done < $WORKDIR/tmp_jamendo_dump

	sed -f $APPDIR/sed_html2txt -i "$STORAGE_DIR/index_jamendo"
	mv -f "$STORAGE_DIR/index_jamendo" "$STORAGE_DIR/index_jamendo"
	#turn on search-filter - off by default
	echo true > $WORKDIR/SEARCH_JAMENDO
	#cleanup
	rm $WORKDIR/tmp_jamendo*
	;;
-jamendo)
	#check if db exists
	if [ ! -s "$STORAGE_DIR"/index_jamendo* ]; then
		echo -e "|$(gettext 'Missing index')|||||||||||||gtk-info\n|$(gettext 'See Setup in')\n|$(gettext 'Music sources menu')" > $WORKDIR/sourcelist
		exit
	fi
	#create list
	echo > $WORKDIR/sourcelist
	for I in {A..Z}; do
		echo "pmusic_jamendo_char:$I|$I" >> $WORKDIR/sourcelist
	done
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;
-jamendo_char)
	#show list of artists
	cut -d'|' -f2 "$STORAGE_DIR"/index_jamendo | grep -i "^$2" | sort -u | awk '{print "pmusic_jamendo_artist:"$1"|"$1}' | uniq > $WORKDIR/sourcelist
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Jamendo browse artist')" & #update history
	echo true > $WORKDIR/UPDATE_SOURCELIST
	;;
-jamendo_artist)
	#show list of albums
	echo 'pmusic_jamendo|..' > $WORKDIR/sourcelist
	grep -F "$2" "$STORAGE_DIR"/index_jamendo* | awk -F "|" '{print "pmusic_jamendo_album:"$4","$2"|"$4"  ("$6")"}' | sort -u -nst'|' -k2,2 >> $WORKDIR/sourcelist
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Jamendo browse album')" &
	echo true > $WORKDIR/UPDATE_SOURCELIST #update source-list
	cp -f $WORKDIR/sourcelist $WORKDIR/sourcelist_jamendo_artist #keep a copy if user wants back
	;;
-jamendo_album)
	echo 'pmusic_jamendo_back|..' > $WORKDIR/sourcelist
	#show list of tracks
	grep -F "${2%,*}" "$STORAGE_DIR/index_jamendo" | grep -F "${2#*,}" | sed "s%+%http://api.jamendo.com/get2/stream/track/redirect/?streamencoding=mp31\&id=%" >> $WORKDIR/sourcelist
#	grep -F "$2" "$STORAGE_DIR/index_jamendo_youtube" >> $WORKDIR/sourcelist
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Jamendo browse tracks')" &
	echo true > $WORKDIR/UPDATE_SOURCELIST #update source-list
	;;
-jamendo_back)
	cp -f $WORKDIR/sourcelist_jamendo_artist $WORKDIR/sourcelist
	$APPDIR/func -add_to_history "pMusic: $(gettext 'Jamendo browse album')" &
	echo true > $WORKDIR/UPDATE_SOURCELIST #update source-list
	;;
-jamendo_manager)
	. $APPDIR/func -reset_gtk
	export pmusic_jamendo='
	<window title="pMusic - '$(gettext 'Jamendo setup')'" icon-name="pmusic">
	<vbox>
	 '"$($APPDIR/func_svg -heading "jamendo.com")"'
	 <notebook labels=" '$(gettext 'Install')' | '$(gettext 'Advanced')' ">
	  <frame>
	   <text><label>"'$(gettext 'The Jamendo index is a file containing the information of all music at jamendo.com. pMusic will play Jamendo tracks without this index file, but it will benefit of it when it comes to browsing and advanced searching.

The index file will be 20Mb+ when installed, and contains info about 300000+ music tracks.')'"</label></text>
	   <hbox homogeneous="true"><hbox>
	    <button name="highlight">
	     <input file stock="gtk-apply"></input>
	     <label>'$(gettext 'Install')'</label>
	     <action>EXIT:install</action>
	    </button>
	   </hbox></hbox>
	  </frame>
	  <frame>
	   <text><label>"'$(gettext 'The installable index may not hold the latest tracks at jamendo.com. You can build the index file yourself of the very recent info.

Depending on your system this process will take from minutes to hours.')'"</label></text>
	   <hbox homogeneous="true"><hbox>  
	    <button>
	     <label>'$(gettext 'Build index')'</label>
	     <action>EXIT:build</action>
	    </button>
	   </hbox></hbox>
	  </frame>
	 </notebook>
	 <hbox>
	  <text use-markup="true"><label>"<b>'$(gettext 'Date of index')':</b>"</label></text>
	  <text><input>find "'$STORAGE_DIR'/index_jamendo" -printf "%Td.%Tb %TY   (%TH:%TM)"</input></text>
	  <text use-markup="true"><label>"  <b>'$(gettext 'Jamendo Tracks')':</b>"</label></text>
	  <text><input>echo -n $(grep -c ^ "'$STORAGE_DIR'/index_jamendo")</input></text>
	  <button cancel></button>
	 </hbox>
	</vbox>
	</window>'
	I=$IFS; IFS=""
	for STATEMENTS in $($GTKDIALOG -p pmusic_jamendo); do
		eval $STATEMENTS
	done
	IFS=$I
	
	case $EXIT in
		install)
			echo "$(gettext 'Downloading Jamendo index.')" > $WORKDIR/splashtext
			$APPDIR/box_splash &
			#check internet connection
			LC_ALL=C wget --spider "$FTP_SERVER/pmusic_index_webmusic_jamendo.gz" 2> $WORKDIR/tmp
			if [ "`grep -Ei "unable to resolve host|file does not exist" $WORKDIR/tmp`" ]; then
				#let's try the alternative ftp server
				LC_ALL=C wget --spider "$FTP_SERVER_2/pmusic_index_webmusic_jamendo.gz" 2> $WORKDIR/tmp
				if [ "`grep -Ei "unable to resolve host|file does not exist" $WORKDIR/tmp`" ]; then
					sleep 0.2
					echo 100 > $WORKDIR/splash
					TXT1="<b>$(gettext 'No connection to server')</b>"
					. $APPDIR/box_ok
					exit
				else
					MY_SERVER="$FTP_SERVER_2"
					MY_USER="$FTP_USER_2"
					MY_PASSWORD="$FTP_PASSWORD_2"
				fi
			else
				MY_SERVER="$FTP_SERVER"
				MY_USER="$FTP_USER"
				MY_PASSWORD="$FTP_PASSWORD"
			fi
			#---
			wget --tries=1 --user $MY_USER --password $MY_PASSWORD --output-document="$STORAGE_DIR/index_jamendo.gz" "$MY_SERVER/pmusic_index_webmusic_jamendo.gz"
			gunzip -f "$STORAGE_DIR/index_jamendo.gz"
			#turn on search-filter - off by default
			echo true > $WORKDIR/SEARCH_JAMENDO
			echo 100 > $WORKDIR/splash
			;;
		build)
			xterm -hold -e $APPDIR/func_jamendo -build_jamendo_index &
			;;
	esac
	;;
esac
	